<template>
  <div class="content-detail">
    <el-card class="card-box">
      <div class="card-box--headerwrap">
        <el-page-header
          icon="el-icon-arrow-left"
          content="填写-施工质量检查"
          @back="handleBack"
        ></el-page-header>
      </div>
    </el-card>

    <el-card class="card-box">
      <el-descriptions
        :column="3"
        size="large"
        title="基础信息"
        class="descriptions"
      >
        <el-descriptions-item
          labelClassName="right-align"
          class-name="my-content"
          label="单据名称"
          >{{ checkInfoData.monomerName }}</el-descriptions-item
        >
        <el-descriptions-item
          labelClassName="right-align"
          class-name="my-content"
          label="工程类型"
          >{{ checkInfoData.atypeName }}</el-descriptions-item
        >
        <el-descriptions-item
          labelClassName="right-align"
          class-name="my-content"
          label="分部"
          >{{ checkInfoData.btypeName }}</el-descriptions-item
        >
        <el-descriptions-item
          labelClassName="right-align"
          class-name="my-content"
          label="子分部"
          >{{ checkInfoData.ctypeName }}</el-descriptions-item
        >
        <el-descriptions-item
          labelClassName="right-align"
          class-name="my-content"
          label="分项"
          >{{ checkInfoData.dtypeName }}</el-descriptions-item
        >
      </el-descriptions>
    </el-card>

    <el-card class="card-box card-table">
      <template #header>
        <div class="card-header">检查项列表</div>
      </template>

      <el-skeleton style="height: 50vh" :rows="8" :loading="loading" animated>
        <el-table
          :data="tableData"
          stripe
          style="width: 100%"
          v-loading="loading"
          :header-cell-style="{
            background: '#F7F9FD',
            color: '#000',
            height: '48px',
            borderTop: '1px soild #E4E8F2'
          }"
        >
          <template #empty>
            <el-empty :image-size="150" description="暂无数据"></el-empty>
          </template>

          <el-table-column type="index" label="序号" width="80">
            <template v-slot="scope">
              <span>{{
                (pageState.pageNum - 1) * pageState.pageSize + scope.$index + 1
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="content" label="检查内容"> </el-table-column>
          <el-table-column prop="requests" label="标准要求"> </el-table-column>
          <el-table-column
            prop="checkMethod"
            label="检查方法"
          ></el-table-column>
          <el-table-column prop="createTime" label="已完成/已检查">
            <template #default="{ row }">
              <span class="times" @click="handleList(row)"
                >{{ row.insFinishTimes }}/{{ row.insTimes }}</span
              >
            </template>
          </el-table-column>

          <el-table-column fixed="right" label="操作">
            <template #default="{ row }">
              <el-button
                type="text"
                size="small"
                @click="handleAdd(row)"
                v-auth="`/projectsS/quality--add`"
                >新建</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-skeleton>
    </el-card>

    <el-dialog
      v-model="showAddCheck"
      title="新建检查反馈（安全技术交底）"
      width="38vw"
      destroy-on-close
      custom-class="add-check"
    >
      <add-check-feed-back
        :checkItem="checkItem"
        ref="formRef"
      ></add-check-feed-back>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddCheck = false">取消</el-button>
          <el-button type="primary" @click="handleSure">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="showCheckList"
      title="检查列表（安全技术交底）"
      width="70%"
      destroy-on-close
      custom-class="check-list"
    >
      <check-list :checkItem="checkItem" @closeList="closeList"></check-list>
    </el-dialog>

    <!-- 检查详情 -->
    <el-dialog
      v-model="showCheckDetail"
      title="检查详情（安全技术交底）"
      width="70%"
      destroy-on-close
      custom-class="check-list check-color"
    >
      <check-detail
        @closeDetail="closeDetail"
        :instanceId="instanceId"
      ></check-detail>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { useRoute, useRouter } from "vue-router";
import { defineComponent, reactive, ref } from "vue";
import NotifMessage from "/@/utils/message/notification";
import addCheckFeedBack from "../components/addCheckFeedBack.vue";
import checkList from "../components/checkList.vue";
import checkDetail from "../components/checkDetail.vue";
import {
  checkInfo,
  checkItemList,
  addCheckRecord,
  flowStart
} from "/@/api/construction";
import { storageLocal } from "/@/utils/storage";
export default defineComponent({
  name: "resourceSet",
  components: { addCheckFeedBack, checkList, checkDetail },
  setup() {
    const formRef = ref<HTMLFormElement | null>(null) as any;
    const router = useRouter();
    const route = useRoute();
    let tableData = ref([]);
    let checkInfoData = ref({});
    let checkId = route.query.id;
    const instanceId = ref();
    const checkItem = ref({});
    const showAddCheck = ref<boolean>(false);
    const showCheckList = ref<boolean>(false);
    const showCheckDetail = ref<boolean>(false);
    const loading = ref<boolean>(false);
    const pageState = reactive({
      pageNum: 1,
      pageSize: 500
    });

    //发起流程
    const flowStartData = reactive({
      formBaseInfo: {
        billName: "",
        projectName: storageLocal.getItem("projectInfo").name,
        projectManageId: storageLocal.getItem("projectInfo").id,
        id: ""
      },
      flowFormData: {
        approvalResult: "不合格",
        businessId: "",
        flowTypeCode: "1015",
        nodeId: "ACT_010",
        projectManageId: storageLocal.getItem("projectInfo").id
      },
      formSubMap: {
        flowType: "1015",
        assignee: null,
        opinion: ""
      }
    });
    // 获取检查项列表
    async function getCheckItemList() {
      try {
        loading.value = true;
        let postData = { qtyCheckId: +checkId, isShow: 1 };
        const { code, data } = await checkItemList({
          ...pageState,
          ...postData
        });
        if (code === 200) {
          tableData.value = data?.list;
        }
      } catch (err) {
        console.log(err);
      } finally {
        loading.value = false;
      }
    }

    // 获取工程质量详情
    const checkDetail = async () => {
      try {
        let postData = { id: checkId };
        const { code, data } = await checkInfo(postData);
        if (code === 200) {
          checkInfoData.value = data;
        }
      } catch (err) {
        console.log(err);
      }
    };

    const onFilterFileData = (list: any[]) => {
      if (!list || !list.length) return;
      const newFileData = list.map(item => {
        return item.response.data;
      });
      return newFileData;
    };

    //新增检查记录
    const handleSure = async () => {
      const isValid = await formRef.value.validate();
      if (!isValid) return;
      const params = await formRef.value.formData;
      const fileList = await formRef.value.formData;
      params.partybHandlerId = params?.partybHandlerInfo?.value;
      params.partybHandlerName = params?.partybHandlerInfo?.label;
      params.jpysAttachmentArr = onFilterFileData(fileList.jpysAttachment);
      params.kzxmclAttachmentArr = onFilterFileData(fileList.kzxmclAttachment);
      params.ysrymdAttachmentArr = onFilterFileData(fileList.ysrymdAttachment);
      params.ysryzpAttachmentArr = onFilterFileData(fileList.ysryzpAttachment);
      if (params.isQualifiedCheck === "1") {
        //合格
        params.approveStatus = 2;
        params.handlerType = 1;
      } else if (params.isQualifiedCheck == "0") {
        //不合格
        params.approveStatus = 1;
        params.handlerType = 2;
      }
      try {
        const { code, data, message } = await addCheckRecord(params);
        if (code === 200) {
          if (params.isQualifiedCheck == "0") {
            checkFlowStart(data, params);
          } else {
            getCheckItemList();
            showAddCheck.value = false;
          }
        } else {
          message && NotifMessage.error(message);
        }
      } catch (err) {
        console.log(err);
      }
    };

    //发起流程
    const checkFlowStart = async (data, params) => {
      flowStartData.formBaseInfo.billName =
        checkInfoData.value.monomerName +
        checkItem.value.content +
        "的检查流程";
      flowStartData.formBaseInfo.id = data;
      flowStartData.flowFormData.businessId = data;
      flowStartData.formSubMap.assignee = params.partybHandlerId;
      flowStartData.formSubMap.opinion = `是否合格:${
        params.isQualifiedCheck === "1" ? "合格" : "不合格"
      }#e#检查小结:${params.insSummary}`;
      if (params?.jpysAttachmentArr?.length) {
        flowStartData.formSubMap.opinion += `#e#举牌验收照片:${JSON.stringify(
          params.jpysAttachmentArr
        )}`;
      }
      flowStartData.formSubMap.opinion += `#e#主要控制项目测量照片:${JSON.stringify(
        params.kzxmclAttachmentArr
      )}`;
      flowStartData.formSubMap.opinion += `#e#验收人员名单:${JSON.stringify(
        params.ysrymdAttachmentArr
      )}`;
      flowStartData.formSubMap.opinion += `#e#验收人员照片:${JSON.stringify(
        params.ysryzpAttachmentArr
      )}`;
      try {
        const { code, message } = await flowStart(flowStartData);
        if (code === 200) {
          getCheckItemList();
          showAddCheck.value = false;
          NotifMessage.success(message);
        } else {
          message && NotifMessage.error(message);
        }
      } catch (err) {
        console.log(err);
      }
    };

    const handleAdd = row => {
      checkItem.value = row;
      showAddCheck.value = true;
    };

    const handleList = row => {
      checkItem.value = row;
      showCheckList.value = true;
    };

    // 返回按钮事件
    const handleBack = () => {
      router.push("/projectsS/construction/quality");
    };

    const closeList = type => {
      showCheckDetail.value = true;
      instanceId.value = type;
    };

    const closeDetail = () => {
      showCheckDetail.value = false;
    };

    if (checkId) {
      checkDetail();
      getCheckItemList();
    }

    return {
      formRef,
      tableData,
      handleBack,
      showAddCheck,
      showCheckList,
      showCheckDetail,
      checkInfoData,
      pageState,
      loading,
      handleAdd,
      handleList,
      checkItem,
      handleSure,
      closeList,
      closeDetail,
      instanceId
    };
  }
});
</script>

<style lang="scss" scoped>
.descriptions {
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #494c53;
  :deep .el-descriptions__header {
    padding: 14px 0 14px 16px;
    border-bottom: 1px solid #c2cade;
  }
  :deep .my-content {
    min-width: 200px;
    padding: 6px 0 6px 12px;
    background: #fdfdff;
    border-radius: 4px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #8895b7;
    font-size: 14px;
    display: inline-block;
  }
}
.card-table {
  height: calc(100% - 48px - 180px);
  .card-header {
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: bold;
    color: #494c53;
  }
  :deep .el-card__body {
    height: calc(100% - 50px);
    .times {
      color: #5298ff;
      cursor: pointer;
    }
  }
}
:deep .add-check {
  .el-dialog__body {
    padding: 20px 40px 8px 10px;
  }
}
:deep .check-list {
  .el-dialog__body {
    padding: 16px;
  }
}
:deep .check-color {
  .el-dialog__body {
    background: #fdfdff;
  }
}
</style>
